package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import Other.Glob;

import database.DatabaseExtension;
import database.MyTax;
import database.NewTirDataBase;
import enums.DialogType;
import enums.SearchType;

public class Tax extends JFrame {
	//variable for singleton
	private static Tax taxInstance = null;
	private JPanel contentPane;
	private JTextField tfCode;
	private JTextField tfName;
	//variable that represent this window frame
	private JFrame thisFrame = this;
	//variable to enable and disable the screen
	boolean disable;
	private JTextField tfType;
	private Tax() {
		//set the title
		setTitle("Tax");
		setVisible(true);
		//set resizable
		setResizable(false);
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 639, 322);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		JPanel mainPanel = new JPanel();
		mainPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addComponent(buttonPanel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addComponent(mainPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
					.addComponent(mainPanel, GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(buttonPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGap(5))
		);
		JButton btnSave = new JButton("F4 Save");
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//Save when button pressed
				saveDialog();
			}
		});
		tfCode = new JTextField();
		tfCode.getInputMap(tfCode.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), "Save");
		tfCode.getActionMap().put("Save", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				//Save when button pressed
				 saveDialog();
			 }
		});
		JButton btnRemove = new JButton("F6 Remove");
		//set up F6 for removing
		btnRemove.getInputMap(btnRemove.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), "");
		btnRemove.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 //remove item when F6 button pressed
				 ScreenHandling.remove(tfCode, SearchType.TAX);
			    }
		});
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//remove item when button pressed
				 ScreenHandling.remove(tfCode, SearchType.TAX);
			}
		});
		JButton btnFReset = new JButton("F7 Reset");
		//set up F7 for reset
		btnFReset.getInputMap(btnFReset.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0), "");
		btnFReset.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				//reset field when button pressed
				 resetFields();
			    }
		});
		btnFReset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//reset field when button pressed
				resetFields();
			}
		});
		JButton btnEscExit = new JButton("Esc Exit");
		//set up Escape for exit
		btnEscExit.getInputMap(btnEscExit.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "");
		btnEscExit.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				if (disable == false){
				//escape from the screen
					escape();
				}
			    }
		});
		btnEscExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//if the screen is disable it is possible to escape
				if (disable == false){
					escape();
				}
			}
		});
		GroupLayout gl_buttonPanel = new GroupLayout(buttonPanel);
		gl_buttonPanel.setHorizontalGroup(
			gl_buttonPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_buttonPanel.createSequentialGroup()
					.addGap(18)
					.addComponent(btnRemove)
					.addPreferredGap(ComponentPlacement.RELATED, 220, Short.MAX_VALUE)
					.addComponent(btnEscExit)
					.addGap(29)
					.addComponent(btnFReset)
					.addGap(34)
					.addComponent(btnSave)
					.addGap(18))
		);
		gl_buttonPanel.setVerticalGroup(
			gl_buttonPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_buttonPanel.createSequentialGroup()
					.addGap(21)
					.addGroup(gl_buttonPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnSave)
						.addComponent(btnRemove)
						.addComponent(btnFReset)
						.addComponent(btnEscExit))
					.addContainerGap(38, Short.MAX_VALUE))
		);
		buttonPanel.setLayout(gl_buttonPanel);
		JLabel codeLabel = new JLabel("Code");
		JLabel lblName = new JLabel("Tax Name");
		//set up F5 for saving only when the text is focused
		tfCode.getInputMap(tfCode.WHEN_FOCUSED)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "");
		tfCode.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 //when textcode focused and f5 pressed search dialog comes up
				search();
			    }
		});
		JButton searchButton = new JButton("F5 Search");
		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				 //when textcode focused and f5 pressed search dialog comes up
				search();
			}
		});
		tfCode.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				//when a number is entered with ENTER
				if(e.getKeyChar() == KeyEvent.VK_ENTER){
					
					enterData();
					
					//tfName.requestFocus();
				}
				
			}
		});
		tfCode.setColumns(10);
		tfName = new JTextField();
		tfName.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				//when a number is entered
				if(e.getKeyChar() == KeyEvent.VK_ENTER){
					//request focus for the next fields
					tfType.requestFocus();	
				}
			}
		});
		tfName.setColumns(10);
		
		JLabel lblType = new JLabel("Type");
		
		tfType = new JTextField();
		tfType.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				//when a type is entered
				if(e.getKeyChar() == KeyEvent.VK_ENTER){
					//request focus for the next fields
					tfCode.requestFocus();				
				}
			}
		});
		tfType.setColumns(10);
		GroupLayout gl_mainPanel = new GroupLayout(mainPanel);
		gl_mainPanel.setHorizontalGroup(
			gl_mainPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addGap(42)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(codeLabel, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblName)
						.addComponent(lblType))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING, false)
						.addComponent(tfType)
						.addComponent(tfName)
						.addComponent(tfCode, GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(searchButton)
					.addContainerGap(284, Short.MAX_VALUE))
		);
		gl_mainPanel.setVerticalGroup(
			gl_mainPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addGap(37)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(codeLabel)
						.addComponent(tfCode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(searchButton))
					.addGap(18)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblName)
						.addComponent(tfName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblType)
						.addComponent(tfType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(52, Short.MAX_VALUE))
		);
		//request focus when object is called
		tfCode.requestFocus(true);
		mainPanel.setLayout(gl_mainPanel);
		contentPane.setLayout(gl_contentPane);	
	}
//singleton
public static Tax getInstance(){
	if(taxInstance == null){
		taxInstance = new Tax();
	}
	return taxInstance;
	}
//initiate data
public void init(MyTax Tax){
	tfCode.setText(Tax.getTaxID());
	tfName.setText(Tax.getTaxName());
	tfType.setText(Tax.getType());
}
//method needed to set focus from other screens
public void setTextCodeFocus(){
	tfCode.requestFocus();
}
//reset fields
public void resetFields(){
	tfCode.setText("");
	tfName.setText("");
	tfType.setText("");
	tfCode.requestFocus();
}
//method needed to get value from text code in other screens
public String getFieldText() {
    return tfCode.getText();
 }
//method for saving the object
public void saveDialog(){
	//Glob.type = SearchType.TAX;
	Glob.setDialog(DialogType.OVERWRITE);
	try{
	if(tfName.getText().trim().length()<1) {
		JOptionPane.showMessageDialog(null, "Name may not be empty");
		tfName.requestFocus();
		return;
	}
	if(!tfCode.getText().trim().isEmpty()) {
		
		if(Integer.parseInt(tfCode.getText())<1){
			JOptionPane.showMessageDialog(null, "Code has to be a valid number");
			tfCode.setText("");
			tfCode.requestFocus();
			return;
			
		}
		}
	//System.out.println("this is the value in type textfield "+  Float.valueOf(tfType.getText()));
	if(!tfType.getText().isEmpty()) {
	try{	
	if(Integer.parseInt(tfType.getText())<=-1){
		JOptionPane.showMessageDialog(null, "Type has to be a positive number");
		tfType.setText("");
		tfType.requestFocus();
		return;
	}
	}catch (NumberFormatException type){
		
		type.printStackTrace();
		JOptionPane.showMessageDialog(null, "Type has to be a positive number");
		tfType.setText(null);
		tfType.requestFocus();
		return;
	}
	}
	ArrayList<Integer> ids = DatabaseExtension.columnIDs("Select * from Tax");
		System.out.println(ids);
		boolean ok = false;
		for (int i: ids) {
			if (i == Integer.parseInt(tfCode.getText()))
					ok=true;
		}		
			if (ok) {
			//JOptionPane.showMessageDialog(null, "This ID is not on the Tax table");
			Dialog d = Dialog.getInstance();
			d.setVisible(true);
			Tax.getInstance().disableTax();
			//tfCode.requestFocus();
			return;
		}else{		
			save();			
		}
		
}catch (NumberFormatException e){
	
	System.out.println("This is the general expetion inside saveDialog");
	JOptionPane.showMessageDialog(null, "Code must be a number");
	tfCode.setText("");
	tfCode.requestFocus();
 e.printStackTrace();
 
}
}
//method that saves the object in the database
public void save(){
	
	Glob.setType(SearchType.TAX);
	String[] data = new String[3];	
	try{
	data[0] = tfCode.getText();	
	}catch(Exception code){
		
		code.printStackTrace();
		
	}
	System.out.println("This is the id got from the tfcode inside save" + data[0]);
	if(data[0].isEmpty()){
	data[0] = null;
	}
data[1] = tfName.getText();

try{
	if(tfType.getText().isEmpty()){
		
		data[2] = "0";
		
	}else{
data[2] = tfType.getText();
	}

}catch(Exception decimal){
	decimal.printStackTrace();
	JOptionPane.showMessageDialog(null, "Type must be a valid integer number");
}

System.out.println("this is the string of data from Tax in the method save" + data[0] + data[1] + data[2]);
	MyTax Tax = new MyTax(data);
	System.out.println("this is the data inside de object in the method save" + Tax.getTaxID() + Tax.getTaxName());
	try{
		DatabaseExtension.saveTax(Tax);
	}catch (Exception saveTax){
		
		saveTax.printStackTrace();
		System.out.println("this is the exception released when type is a letter");
		
		
	}
		resetFields();
		setTextCodeFocus();

}
//method that calls the searchwindow
public void search(){
	Glob.setType(SearchType.TAX);
	//System.out.println("This is the globa variable in Tax when pressing search button" + Glob.type);

	//MyTax Tax = new MyTax(); 
	SearchWindow s = SearchWindow.getInstance();
	s.setTitle();
	s.setVisible(true);
	disableTax();
}
//method to disable the screen
public void disableTax(){
	Tax.getInstance().disable();
	disable = true;
}
//method to enable the screen
public void enableTax(){
	Tax.getInstance().enable();
	disable = false;
	tfCode.requestFocus();
	Tax.getInstance().toFront();
}
//method to get the disable boolean
public boolean getDisable(){
	return disable;
}

//method that populates the screen fields with the object
public void enterData(){
	try{
		//set up global variable for the Tax screen
		Glob.setType(SearchType.TAX);
		//if textfield is 0 or less than 0
		if(tfCode.getText().trim().length()<1){
			tfName.requestFocus();
		}
		else if(Integer.parseInt(tfCode.getText()) <= 0){
			JOptionPane.showMessageDialog(null, "Code must be a positive number");
			tfCode.setText("");
			tfCode.requestFocus();
			return;
		}
	//Select the row that will populate the screen
	NewTirDataBase t = (MyTax) DatabaseExtension.getTableID("SELECT * FROM Tax WHERE TaxID = '" + tfCode.getText() +"'")[0];
	System.out.println(((MyTax) t).getTaxID());
	//populating the fields
	tfName.setText(((MyTax) t).getTaxName());
	
	try{
	//if(Integer.valueOf(tfType.getText()) <= 0){
		System.out.println("This is the value of the type field" + tfType.getText());
		//JOptionPane.showMessageDialog(null, "Type must be a positive number");
		//tfType.setText("");
		//tfType.requestFocus();
		//return;
	//}
	tfType.setText(String.valueOf(((MyTax) t).getType()));
	}catch(Exception e){
		System.out.println("This is the exception regarding the tax type");
		e.printStackTrace();
	}
	//System.out.println("this is the Tax id and name" + c.getTaxID() + c.getTaxName());
	System.out.println("intro has been pressed");
	//requestfocus for the next field when pressing enter
	tfName.requestFocus();
	}catch(ArrayIndexOutOfBoundsException exception){
		System.out.println("This is the exception release when id not in database");
		//if there is no id in the database tfName set to empty
		tfName.setText(null);
		exception.printStackTrace();
		//requestfocus for the next field when pressing enter
		tfName.requestFocus();
	}catch(NumberFormatException exception){
		//if code tf is empty

		JOptionPane.showMessageDialog(null, "Code must be a positive number");
		tfCode.setText(null);
		System.out.println("This is the exception release when there is an String");
		exception.printStackTrace();
	}catch(Exception exception){
		System.out.println("General Exception");
		exception.printStackTrace();
	}
}
//method to close the screen
public void escape(){
	Tax.getInstance().dispose();
	Menu.getInstance().enableMenu();
}
}
